'use strict';

/**
 * @ngdoc service
 * @name webApp.promise
 * @description
 * # promise
 * Service in the webApp.
 */

//登录
angular.module('webApp')
  .service('promiseSignIn', function (Restangular,client_id,client_secret,grant_type,searchParam) {
    //路由
    var rootUrl = Restangular.one('v2');
    //头
    var formHead = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    //序列化
    var param = function(obj) {
      var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
      for(name in obj) {
        value = obj[name];
        if(value instanceof Array) {
          for(i=0; i<value.length; ++i) {
            subValue = value[i];
            fullSubName = name + '[' + i + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if(value instanceof Object) {
          for(subName in value) {
            subValue = value[subName];
            fullSubName = name + '[' + subName + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if(value !== undefined && value !== null)
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
      return query.length ? query.substr(0, query.length - 1) : query;
    };
    //登录
    this.signIn = function(data){
      data.client_id = client_id;
      data.client_secret = client_secret;
      data.grant_type = grant_type;
      if(!data.username){
        data.username = data.email;
      }
      delete data['email'];
      delete data['password_confirmation'];
      if(searchParam.getUrl('avatar_url') && searchParam.getUrl('token')){
        data.avatar_url = searchParam.getUrl('avatar_url');
        data.token = searchParam.getUrl('token');
      }
      return rootUrl.post('oauth/access-token',param(data),{},formHead);
    };
  });

//首页
angular.module('webApp')
  .service('promiseHome', function (Restangular,client_id,client_secret,grant_type,searchParam,cookie,popBox) {
    //路由
    var rootUrl = Restangular.one('v2');
    var getArt = Restangular.one('v2','articles');
    var auto = Restangular.one('v2', 'entry');
    //头
    var formHead = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    //序列化
    var param = function(obj) {
      var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
      for(name in obj) {
        value = obj[name];
        if(value instanceof Array) {
          for(i=0; i<value.length; ++i) {
            subValue = value[i];
            fullSubName = name + '[' + i + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if(value instanceof Object) {
          for(subName in value) {
            subValue = value[subName];
            fullSubName = name + '[' + subName + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if(value !== undefined && value !== null)
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
      return query.length ? query.substr(0, query.length - 1) : query;
    };
    //第三方自动登录
    this.thirdAutoSignIn = function() {
      return auto.get({
        token: searchParam.getUrl('token')
      });
    };
    //第三方自动登录
    this.signIn = function(data){
      data.client_id = client_id;
      data.client_secret = client_secret;
      data.grant_type = grant_type;
      if(!data.username){
        data.username = data.email;
      }
      delete data['email'];
      delete data['password_confirmation'];
      if(searchParam.getUrl('avatar_url') && searchParam.getUrl('token')){
        data.avatar_url = searchParam.getUrl('avatar_url');
        data.token = searchParam.getUrl('token');
      }
      auto.get({
        token: searchParam.getUrl('token')
      }).then(function(data){
        data.client_id = client_id;
        data.client_secret = client_secret;
        data.grant_type = grant_type;
        rootUrl.post('oauth/access-token',param(data),{},formHead).then(function(data){
          cookie.setCookie('access_token',data.access_token,'s' + data.expires_in);
          popBox.showConfirm('提示','第三方登录成功！');
        });
      });
    };
    //首页新闻
    this.homeData = function(page,per_page){
      return getArt.customGET('',{
        page: page,
        per_page: per_page
      });
    };
  });

//报告
angular.module('webApp')
  .service('promiseReport', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    var getArt = Restangular.one('v2','articles');
    //报告
    this.reportData = function(){
      return rootUrl.customGET('reports');
    };
    //收藏
    this.stars = function(id){
      return getArt.customPUT({},id + '/stars?' +  Math.random());
    };
  });

//正文
angular.module('webApp')
  .service('promiseMainText', function (Restangular) {
    var getArt = Restangular.one('v2','articles');
    //正文信息
    this.articleMain = function(id){
      return getArt.customGET(id,{'': Math.random()});
    };
  });

//搜索
angular.module('webApp')
  .service('promiseSearch', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //搜索
    this.search = function(q,page,per_page){
      return rootUrl.customGET('search/articles?' + Math.random(),{
        'q': q,
        'page': page,
        'per_page': per_page
      });
    };
  });

//团队
angular.module('webApp')
  .service('promiseTeam', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //团队
    this.teams = function(page,per_page){
      return rootUrl.customGET('teams',{
        'page': page,
        'per_page': per_page
      });
    };
  });

//产品
angular.module('webApp')
  .service('promiseProduct', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //产品
    this.products = function(){
      return rootUrl.customGET('products');
    };
  });

//第三方
angular.module('webApp')
  .service('promiseThirdSignIn', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //第三方
    this.thirdSignIn = function(data){
      return rootUrl.customGET(data);
    };
  });

//修改密码
angular.module('webApp')
  .service('promiseModifyPassWord', function (Restangular) {
    var user = Restangular.one('v2','user');
    //修改密码
    this.modifyPassWord = function(data){
      return user.customPUT({
        'old_password': data.old_password,
        'new_password': data.new_password,
        'new_password_confirmation': data.new_password_confirmation
      },'password');
    };
  });

//忘记密码
angular.module('webApp')
  .service('promiseForgetPassword', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    this.forgetPassword = function(email,captcha,token){
      return rootUrl.customPOST({
        'email': email ,
        'captcha': captcha,
        'token': token
      },'send/emails')
    };
  });

//更多报告
angular.module('webApp')
  .service('promiseMoreReport', function (Restangular) {
    var rootUrl = Restangular.one('v2','more_articles');
    this.moreReport = function(id){
      return rootUrl.customGET(id)
    };
  });

//忘记密码重置密码
angular.module('webApp')
  .service('promiseResetPassword', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //忘记密码后重置密码
    this.resetPassword = function(password,password_confirmation,confirmation){
      return rootUrl.customPUT({
        'password': password ,
        'password_confirmation': password_confirmation,
        'confirmation': confirmation
      },'reset/password')
    };
  });

//联系我们
angular.module('webApp')
  .service('promiseGetContacts', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //联系我们
    this.getContacts = function(){
      return rootUrl.customGET('contacts');
    };
  });

//修改头像
angular.module('webApp')
  .service('promiseImgCrop', function (Restangular) {
    var user = Restangular.one('v2','user');
    //联系我们
    this.modifyImgCrop = function(base64){
      return user.customPOST({
        'avatar_url': base64
      });
    };
  });

//评论和收藏
angular.module('webApp')
  .service('promiseFooter', function (Restangular,$location,cookie) {
    var getArt = Restangular.one('v2','articles');
    //收藏文章
    this.stars = function(){
      return getArt.customPUT({},cookie.getCookie('newsId') + '/stars?' + Math.random());
    };
    //取消收藏文章
    this.deleteStars = function(){
      return getArt.customDELETE(cookie.getCookie('newsId') + '/stars?' + Math.random());
    };
    //文章评论
    this.textMainComments = function(content,captcha,token,flag){
      if(cookie.getCookie('access_token')){
        return getArt.customPOST({
          'content': content,
          'flag': flag
        },cookie.getCookie('newsId') + '/comments');
      }
      else{
        return getArt.customPOST({
          'content': content,
          'captcha': captcha,
          'token': token,
          'flag': flag
        },cookie.getCookie('newsId') + '/comments')
      }
    };
    //回复与匿名回复
    this.replay = function(content,captcha,token,flag){
      //非社区
      if($location.$$path != '/root/community'){
        if(cookie.getCookie('access_token') && cookie.getCookie('replayId') && cookie.getCookie('newsId')){
          return getArt.customPOST({
            'content': content,
            'flag': flag
          },cookie.getCookie('newsId') + '/comments/'+ cookie.getCookie('replayId') +'/replies');
        }
        else if(!cookie.getCookie('access_token') && cookie.getCookie('replayId') && cookie.getCookie('newsId')){
          return getArt.customPOST({
            'content': content,
            'captcha': captcha,
            'token': token,
            'flag': flag
          },cookie.getCookie('newsId') + '/comments/'+ cookie.getCookie('replayId') +'/anonymous_replies');
        }
      }
      //社区
      else if($location.$$path == '/root/community'){
        if(cookie.getCookie('access_token') && cookie.getCookie('replayId') && cookie.getCookie('newsId')){
          return getArt.customPOST({
            'content': content,
            'flag': flag
          },1 + '/comments/'+ cookie.getCookie('replayId') +'/replies',{type: 'c'});
        }
        else if(!cookie.getCookie('access_token') && cookie.getCookie('replayId') && cookie.getCookie('newsId')){
          return getArt.customPOST({
            'content': content,
            'captcha': captcha,
            'token': token,
            'flag': flag
          },1 + '/comments/'+ cookie.getCookie('replayId') +'/anonymous_replies',{type: 'c'});
        }
      }
    };
  });

//社区
angular.module('webApp')
  .service('promiseCommunity', function (Restangular,cookie) {
    var rootUrl = Restangular.one('v2');
    //标签
    this.getTags = function(kind){
      return rootUrl.customGET('tags',{
        'type': kind
      });
    };
    //社区评论1/article_comments/{tags}
    this.getCommunityComment = function(tags){
      var k = '';
      for(var i = 0;i < tags.length;i++){
        k += tags[i] + ',';
      }
      if (cookie.getCookie('access_token')) {
        return rootUrl.customGET('article_comments/' + k);
      }
      else {
        return rootUrl.customGET('article_comments/' + k);
      }
    };
  });

//更多/新闻栏
angular.module('webApp')
  .service('promiseMore', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    var getArt = Restangular.one('v2','articles');
    //更多
    this.moreArticles = function(id){
      return rootUrl.customGET('more_articles/' + id,{'': Math.random()});
    };
    this.stars = function(id) {
      return getArt.customPUT({},id + '/stars?' +  Math.random());
    }
  });

//用户栏
angular.module('webApp')
  .service('promiseUserTable', function (Restangular,cookie) {
    var rootUrl = Restangular.one('v2');
    var user = Restangular.one('v2','user');
    //我的消息
    this.userInformations = function(page,per_page){
      return user.customGET('informations',{
        'page': page,
        'per_page': per_page
      });
    };
    //退出登录
    this.signOut = function(){
      return rootUrl.customDELETE('oauth/invalidate-token',{},{
        'Authorization': cookie.getCookie('access_token')
      });
    };
    //获取用户信息
    this.getUserData = function(){
      return rootUrl.customGET('user',{'': Math.random()});
    };
  });

//个人信息
angular.module('webApp')
  .service('promiseUserData', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //获取用户信息
    this.getUserData = function(){
      return rootUrl.customGET('user',{'': Math.random()});
    };
  });

//评论指令
angular.module('webApp')
  .service('promiseCommunicate', function (Restangular,$location,cookie) {
    var getArt = Restangular.one('v2','articles');
    //点赞
    this.favours = function(id,boole,flag){
      if($location.$$path != '/root/community'){
        if(cookie.getCookie('access_token') && boole == false){
          return getArt.customPUT({},cookie.getCookie('newsId') + '/comments/'+ id +'/favours',{flag: flag});
        }
        else if(cookie.getCookie('access_token') && boole == true){
          return getArt.customDELETE(cookie.getCookie('newsId') + '/comments/'+ id +'/favours',{flag: flag});
        }
      }
      else{
        if(cookie.getCookie('access_token') && boole == false){
          return getArt.customPUT({},1 + '/comments/'+ id +'/favours',{type: 'c',flag: flag});
        }
        else if(cookie.getCookie('access_token') && boole == true){
          return getArt.customDELETE(1 + '/comments/'+ id +'/favours',{type: 'c',flag: flag});
        }
      }
    };
  });

//用户收藏
angular.module('webApp')
  .service('promiseUserCollection', function (Restangular) {
    var user = Restangular.one('v2','user');
    //我的收藏
    this.userCollection = function(page,per_page){
      return user.customGET('stars',{
        'page': page,
        'per_page': per_page,
        '': Math.random()
      });
    };
  });

//我的评论
angular.module('webApp')
  .service('promiseUserCommunicate', function (Restangular) {
    var user = Restangular.one('v2','user');
    //我的评论
    this.usercomments = function(page,per_page){
      return user.customGET('comments',{
        'page': page,
        'per_page': per_page,
        '': Math.random()
      });
    };
  });

//我的消息
angular.module('webApp')
  .service('promiseUserInformation', function (Restangular) {
    var user = Restangular.one('v2','user');
    //我的消息
    this.userInformations = function(page,per_page){
      return user.customGET('informations',{
        'page': page,
        'per_page': per_page,
        '': Math.random()
      });
    };
  });

//注册
angular.module('webApp')
  .service('promiseRegistered', function (Restangular,client_id,client_secret,grant_type,searchParam) {
    var formHead = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    //序列化
    var param = function(obj) {
      var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
      for(name in obj) {
        value = obj[name];
        if(value instanceof Array) {
          for(i=0; i<value.length; ++i) {
            subValue = value[i];
            fullSubName = name + '[' + i + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if(value instanceof Object) {
          for(subName in value) {
            subValue = value[subName];
            fullSubName = name + '[' + subName + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if(value !== undefined && value !== null)
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
      return query.length ? query.substr(0, query.length - 1) : query;
    };
    var user = Restangular.one('v2','user');
    var rootUrl = Restangular.one('v2');
    //注册
    this.registered = function(data){
      data.client_id = client_id;
      data.client_secret = client_secret;
      if(searchParam.getUrl('avatar_url') && searchParam.getUrl('token')){
        data.avatar_url = searchParam.getUrl('avatar_url');
        data.token = searchParam.getUrl('token');
      }
      return rootUrl.post('users',data);
    };
    //登录
    this.signIn = function(data){
      data.client_id = client_id;
      data.client_secret = client_secret;
      data.grant_type = grant_type;
      if(!data.username){
        data.username = data.email;
      }
      delete data['email'];
      delete data['password_confirmation'];
      if(searchParam.getUrl('avatar_url') && searchParam.getUrl('token')){
        data.avatar_url = searchParam.getUrl('avatar_url');
        data.token = searchParam.getUrl('token');
      }
      return rootUrl.post('oauth/access-token',param(data),{},formHead);
    };
  });

// 验证码
angular.module('webApp')
  .service('promisePopImg', function (Restangular) {
    var rootUrl = Restangular.one('v2');
    //验证码
    this.captcha = function(){
      return rootUrl.customGET('generate_token',{'': Math.random()});
    };
  });

//文章评论
angular.module('webApp')
  .service('promiseTextCommunicate', function (Restangular,cookie) {
    var getArt = Restangular.one('v2','articles');
    //获取文章评论
    this.getComments = function(){
      if(cookie.getCookie('access_token')){
        return getArt.customGET(cookie.getCookie('newsId') + '/comments',{'': Math.random()});
      }
      else{
        return getArt.customGET(cookie.getCookie('newsId') + '/comments',{'': Math.random()})
      }
    };
  });
